import time
from fastapi import APIRouter,Depends
from sqlalchemy.orm import Session
from sqlalchemy import desc,asc,and_
from model.downhole_mine import GroundMine as MineTable,FormBody,EditBody
from model.downhole_colliery import GroundColliery
from db.mysql import get_db
from loguru import logger
from vendor.extend.courier import *
from vendor.extend.conversion import is_positive_integer

V3GroundMine = APIRouter()

@V3GroundMine.post('/add')
async def add_mine(item:FormBody,db: Session = Depends(get_db)):
    itme = item.dict()
    colliery_id=itme.get('colliery_id',0)
    if not is_positive_integer(colliery_id):
        return Error(msg='矿井ID参数错误')
    ground = db.query(GroundColliery.id).filter_by(id=colliery_id).first()
    if not ground:
        return Error(msg='矿井不存在')

    add_data=MineTable(
        colliery_id=colliery_id,
        serial_number=itme.get('serial_number',''),
        modem= itme.get('modem',''),
        distance=itme.get('distance',''),
        x=itme.get('x',0),
        y=itme.get('y',0),
        z=itme.get('z',0),
        create_time=int(time.time())
    )
    try:
        # 执行一些数据库操作
        db.add(add_data)
        db.flush()
        db.commit()
        db.refresh(add_data)
    except Exception as e:
        # 手动回滚会话并重新抛出异常
        db.rollback()
        logger.error("钻孔信息 添加 出错:{}", e)
        return Error(msg='钻孔添加错误',data=str(e))

    return Success(msg='钻孔添加成功',data={'mine_id':add_data.id,'create_time':add_data.create_time})


@V3GroundMine.post('/edit')
async def edit_mine(item:EditBody,db: Session = Depends(get_db)):
    item_dict = item.dict()

    edit_data={
        'serial_number':item_dict.get('serial_number',''),
        'modem':item_dict.get('modem',''),
        "x":item_dict.get('x',0),
        "y":item_dict.get('y',0),
        "z":item_dict.get('z',0),
        'distance':item_dict.get('distance',''),
        'update_time':int(time.time())
    }

    try:
        # 执行一些数据库操作
        db.query(MineTable).filter_by(id=item_dict.get('mine_id',0)).update(edit_data)
        db.commit()
    except Exception as e:
        # 手动回滚会话并重新抛出异常
        db.rollback()
        logger.error("钻孔信息 更新 出错:{}", e)
        return Error(msg='钻孔数据更新错误',data=str(e))

    return Success(msg='更新成功',data=edit_data)


@V3GroundMine.get('/getlist')
async def colliery_list(colliery_id:int=0,db: Session = Depends(get_db)):
    if not is_positive_integer(colliery_id):
        return Error(msg='矿井ID参数错误')
    data_list=db.query(MineTable).filter_by(colliery_id=colliery_id).order_by(MineTable.id.desc()).all()
    list_data=[]
    for info in data_list:
        list_data.append({
            "id":info.id,
            "colliery_id":info.colliery_id,
            "serial_number":info.serial_number,
            "x":info.x,
            "y":info.y,
            "z":info.z,
            "modem":info.modem,
            "distance":info.distance,
            "create_time":info.create_time,
        })
    return Success(msg='钻孔列表',data=list_data)